﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Data;
using VAdvantage.Grids;
using VAdvantage.Editor;
using VAdvantage.Classes;
using System.Windows;
using System.Windows.Media;

namespace VAdvantage.Controls
{
    public class VRichTextBox : CTextBox, IControl
    {


        //public static readonly DependencyProperty TextProperty =
        //  DependencyProperty.Register("Text", typeof(String), typeof(VRichTextBox),new PropertyMetadata(TextChanged));
         


        //public String Text
        //{
        //    get
        //    {
        //        return ((String)GetValue(VRichTextBox.TextProperty));
        //    }
        //    set
        //    {
        //        SetValue(VRichTextBox.TextProperty, value);
        //    }

        //}

        //private static void TextChanged (object o,DependencyPropertyChangedEventArgs e)
        //{
        //    ((VRichTextBox)o).TextChanged(e.NewValue);

        //}

        //private void TextChanged(object val)
        //{
        //    //


        //}

        /// <summary>
        /// std Constructor
        /// </summary>
        public VRichTextBox()
        {
            this.AcceptsReturn = true;
            this.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            this.TextWrapping = System.Windows.TextWrapping.Wrap;
        }

        #region "Declaration"
       // VAdvantage.Framework.Editor editor;
        private String _columnName;
        private String _oldText;
        private String _initialText;
        private String _VFormat;
        /** Field Length				*/
        private int _fieldLength;
        /**	Obcure Setting				*/
        //private Obscure m_obscure = null;
        private volatile bool _setting = false;
        /**	Field in focus				*/
        private volatile bool m_infocus = false;
        private bool _mandatory = false;
        private bool _readOnly = false;
        private GridField _field;
        private int _displayType;
        ContextMenuStrip popupMenu = null;
        MenuItem menuEditor;

        private bool _focus;

        System.Windows.Data.Binding binding;

        private SolidColorBrush backColor = new SolidColorBrush();

        #endregion


        public event EventHandler VetoableChangeListener;
        /// <summary>
        /// std Construtor
        /// </summary>
        /// <param name="columnName"></param>
        /// <param name="mandatory"></param>
        /// <param name="isReadOnly"></param>
        /// <param name="isUpdateable"></param>
        /// <param name="displayLength"></param>
        /// <param name="fieldLength"></param>
        /// <param name="VFormat"></param>
        /// <param name="ObscureType"></param>
        public VRichTextBox(String columnName, bool mandatory, bool isReadOnly, bool isUpdateable,
        int displayLength, int fieldLength, int displayType) :this()
        {
            ///this.Size = new System.Drawing.Size(500, 70);
            _readOnly = isReadOnly;
            _mandatory = mandatory;
            _columnName = columnName;
           // this.Name = _columnName;
            if (isReadOnly || !isUpdateable)
            {
                SetReadOnly(true);
            }
            else
            {
                SetReadOnly(false);
            }

           // this.Width = displayLength < 30 ? 300 : 500;

            if (displayType != DisplayType.Memo)
            {
                if (displayType == DisplayType.TextLong)
                {
                    this.Height = 70;
                }
                else
                {
                    this.Height = fieldLength < 300 ? 30 : (fieldLength < 2000) ? 40 : 70;
                }
            }
            else
            {
                try
                {
                    this.Height = fieldLength < 300 ? 30 : (fieldLength < 2000) ? 40 : (fieldLength / 60) * 2;

                }
                catch
                {
                    this.Height = fieldLength < 300 ? 30 : (fieldLength < 2000) ? 40 : 70;
                }
            }
            if (!DataBase.GlobalVariable.IsVisualEditor)
            {
                SetPopUp();
            }
            
            this.MaxLength = fieldLength;
            this.TextChanged += OnTextChanged;
            //this.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
           
        }

        protected  void OnTextChanged(object sender, TextChangedEventArgs e)
        {
            if (!_setting)
            {
                // base.OnTextChanged(e);

                //if (EditingControlDataGridView != null)
                //{
                //    EditingControlValueChanged = true;
                //    EditingControlDataGridView.NotifyCurrentCellDirty(true);
                //    //EditingControlDataGridView.CurrentCell.Value = GetValue();
                //}

                SetColor();

                if (VetoableChangeListener != null)
                {
                    VetoableChangeListener(this, e);
                }
            }
        }

        //Dispose
        
        /// <summary>
        /// Set ContextMenu Strip
        /// </summary>
        public void SetPopUp()
        {
            if (_field != null && _field.GetFieldLength() > _field.GetDisplayLength())
            {
                menuEditor = new MenuItem();
                menuEditor.Header = Utility.Msg.GetMsg(Utility.Envs.GetContext(), "Editor", true);
                menuEditor.Icon = Utility.Envs.GetImageIcon("Editor16.png");
                popupMenu = new ContextMenuStrip();
                
                ContextMenuService.SetContextMenu(this, popupMenu);

                if (menuEditor != null)
                {
                    menuEditor.Click +=new RoutedEventHandler(menuEditor_Click);
                    popupMenu.Items.Add(menuEditor);
                }
            }
        }

        void menuEditor_Click(object sender, RoutedEventArgs e)
        {
            //menuEditor.Enabled = false;
            ////store field header text,fields length according type,control text,control
            //string s = Framework.Editor.StartEditor(Utility.Msg.GetMsg(Utility.Envs.GetContext(), _field.GetHeader(), true), GetText(), _readOnly, _field.GetFieldLength());
            //this.Text = s;
            //menuEditor.Enabled = true;
        }

       

         #region IControl

        /** Mandatory (default false)   */
        public bool GetIsMandatory()
        {
            return _mandatory;
        }
        public void SetIsMandatory(bool value)
        {
            _mandatory = value;
        }
        public bool GetIsReadonly()
        {
            return _readOnly;
        }
        public GridField GetField()
        {
            return _field;
        }
        public void SetField(GridField field)
        {
            _field = field;
            //if (_field != null && Model.MRole.GetDefault().IsShowPreference() && (_displayType == DisplayType.String))
            //{
            //    String columnName = _field.GetColumnName();
            //    if ("Name".Equals(columnName) || "Value".Equals(columnName) || "DocumentNo".Equals(columnName))
            //    { ;}
            //    else
            //    {
            //        // Framework.ValuePreference.AddPreferenceMenuItem(this.preferenceItem_Click, popupMenu);
            //    }
            //}

        }
        public int GetDisplayType()
        {
            return _displayType;
        }
        public void SetDisplayType(int displayType)
        {
            _displayType = displayType;
        }
        public string GetName()
        {
            return this._columnName;
        }
        public object GetValue()
        {
            return this.Text;
        }
        public string GetText()
        {
            return this.Text;
        }
        public string GetSelectedText()
        {
            return this.SelectedText;
        }

        /// <summary>
        /// Set value
        /// </summary>
        /// <param name="value">value</param>
        public void SetValue(object value)
        {
            if (value == null)
                this.Text = "";
            else
                this.Text = value.ToString();
            SetColor();
        }

        public void SetReadOnly(bool readOnly)
        {
            _readOnly = readOnly;
            this.IsReadOnly = readOnly;
            this.IsTabStop = !readOnly;

            SetBackGround(readOnly);
        }
      
        public void SetBackGround(bool value)
        {
            if (value)
            {
                backColor.Color = DataBase.GlobalVariable.READONLY_TEXT_BACK_COLOR;
                this.Background = backColor;
            }
            else
            {
                backColor.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                this.Background = backColor;
                SetColor();
            }
        }

        public void SetName(string name)
        {
            this._columnName = name;
        }

        public bool IsDisabled()
        {
            return !this.IsEnabled;
        }

        public void SetDisabled(bool disabled)
        {
            this.IsEnabled = !disabled;
        }

        public int GetTabIndex()
        {
            return this.TabIndex;
        }

        public void SetTabindex(int tabindex)
        {
            this.TabIndex = tabindex;
        }

        public bool Visible
        {
            get
            {
                return this.Visibility == System.Windows.Visibility.Visible;
            }
            set
            {
                this.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }
        }

        public bool Focused
        {
            get { return _focus; }
        }

        public bool Multiline
        {
            get;
            set;
        }


        private void SetColor()
        {
            if (_mandatory)
            {
                if (this.Text == "")
                {
                    backColor.Color =  DataBase.GlobalVariable.MANDATORY_TEXT_BACK_COLOR;
                    this.Background = backColor;
                }
                else
                {
                    backColor.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                    this.Background = backColor;
                    if (_field != null)
                        _field.SetError(false);
                }
            }
        }

        #endregion

       

        protected override void OnGotFocus(RoutedEventArgs e)
        {
            base.OnGotFocus(e);
            _focus = true;
        }

        protected override void OnLostFocus(RoutedEventArgs e)
        {
            base.OnLostFocus(e);
            _focus = false;
        }

        public void Dispose()
        {
            _field = null;
            if (popupMenu != null)
                popupMenu.Items.Clear();
            popupMenu = null;
            binding = null;
        }

        public String BindValue
        {
            set
            {
                binding = new Binding(value);
                binding.Mode = BindingMode.OneWay;
                this.SetBinding(TextBox.TextProperty,binding);
            }
        }
    }
}
